type SubCallBack =  (...payload:any[])=>void;

type SubMap = {
	[propName: string]: SubCallBack[]
}
interface PublisherInstanceType {
	_subMap: SubMap;
	on: (type:string, cb: SubCallBack )=>void;
	unsubscribe: (type:string, cb: SubCallBack )=>void;
	emit: (type:string, ...payload:any[])=>void;
}

class Publisher implements PublisherInstanceType{
	public _subMap: SubMap;
	static instance: any;
	constructor(){
		this._subMap = {}
	}
	static getInstance(){
		if(!Publisher.instance){
			Publisher.instance = new Publisher();
		}
		return Publisher.instance
	}
	on(type:string, cb: SubCallBack ){
		if(this._subMap[type] && this._subMap[type].indexOf(cb)==-1){
			//如果存在key并且无重复的回调就直接push
			this._subMap[type].push(cb);
		}else{
			this._subMap[type] = [cb];
		}
	}
	unsubscribe(type:string, cb: SubCallBack ){
		if(this._subMap[type]){
			const index = this._subMap[type].indexOf(cb);
			if(index>-1)this._subMap[type].splice(index,1);
		}
	}
	emit(type:string, ...payload:any[] ){
		if(this._subMap[type]){
			this._subMap[type].forEach(cb=>cb(...payload))
		}
	}
}

export default Publisher.getInstance()